package net.qiqbframework.modelling.recording;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.qiqbframework.commandhandling.CommandMessage;
import net.qiqbframework.common.security.AuthUserProvider;
import net.qiqbframework.modelling.command.AggregateHandlingMonitor;
import org.javers.core.Javers;
import org.javers.core.diff.Diff;

/**
 * 聚合变化记录
 */
@Slf4j
public class AggregateChangesRecorder implements AggregateHandlingMonitor {

    private final AuthUserProvider authUserProvider;

    private final Javers javers;
    @Setter
    private boolean javersCommitted = false;

    public AggregateChangesRecorder(AuthUserProvider authUserProvider, Javers javers) {
        this.authUserProvider = authUserProvider;
        this.javers = javers;
    }

    @Override
    public <T> void afterCommit(CommandMessage<?> commandMessage, T beforeHandleAggregateRoot, T afterHandleAggregateRoot) {
        if (javersCommitted) {
            javers.commit(authUserProvider.getAuthUser(), afterHandleAggregateRoot);
        }

        final Diff compare = javers.compare(beforeHandleAggregateRoot, afterHandleAggregateRoot);
        log.info("The user [{}] modified the aggregation root  through a command [{}]", authUserProvider.getAuthUser(), commandMessage.getCommandName());
        log.info(compare.prettyPrint());

    }
}
